import { contextBridge, ipcRenderer } from 'electron'

// --- 定义暴露给渲染进程的API ---
export const electronAPI = {
  resizeWindow: () => {
    ipcRenderer.send('resize-window')
  },

  showTitlebar: () => {
    ipcRenderer.send('show-titlebar')
  },

  hideTitlebar: () => {
    ipcRenderer.send('hide-titlebar')
  },

  minimizeWindow: () => {
    ipcRenderer.send('minimize-window')
  },

  toggleMaximize: () => {
    ipcRenderer.send('toggle-maximize')
  },

  closeWindow: () => {
    ipcRenderer.send('close-window')
  },

  onWindowStateChange: (callback: (state: { isMaximized: boolean }) => void) => {
    const listener = (event: any, state: any) => callback(state);
    ipcRenderer.on('window-state-changed', listener);
    return () => {
      ipcRenderer.removeListener('window-state-changed', listener);
    };
  },

  /**
   * 注册一个回调函数，当主进程推送端口更新时调用。
   * @param callback (ports: { masterPort: number, childPort: number, websocketPort: number }) => void
   * @returns 一个可以用来移除监听器的函数
   */
  onPortsUpdate: (callback: (ports: any) => void) => {
    const listener = (event: any, ports: any) => callback(ports);
    ipcRenderer.on('server-ports-update', listener);

    // 返回一个清理函数，允许渲染进程在组件卸载时停止监听
    return () => {
      ipcRenderer.removeListener('server-ports-update', listener);
    };
  },

  /**
   * 主动获取当前的端口信息
   * @returns Promise<{ masterPort: number, childPort: number, websocketPort: number } | null>
   */
  getServerPorts: () => {
    return ipcRenderer.invoke('get-server-ports');
  },

  /**
   * 获取当前进程ID（用于调试）
   */
  getProcessId: () => {
    return process.pid;
  }
};

// 将 electronAPI 暴露给渲染进程
contextBridge.exposeInMainWorld('electronAPI', electronAPI);
// 声明渲染进程中可用的类型定义
declare global {
  interface Window {
    electronAPI: typeof electronAPI;
  }
}